package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import javax.swing.*;
import java.util.List;

@DubboService
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override//将好友关系表添加到好友表
    public void save( Long friendId,Long userId) {
        //保存之前先判断一下好友关系是否存在
        Criteria criteria1 = Criteria.where("userId").is(userId).and("friendId").is(friendId);
        Query query1 = Query.query(criteria1);
        if (!mongoTemplate.exists(query1, Friend.class)) {
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
        Criteria criteria2 = Criteria.where("userId").is(friendId).and("friendId").is(userId);
        Query query2 = Query.query(criteria1);
        if (!mongoTemplate.exists(query2, Friend.class)) {
            Friend friend2 = new Friend();
            friend2.setUserId(friendId);
            friend2.setFriendId(userId);
            friend2.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend2);
        }
    }

    @Override//查询全部好友列表
    public List<Friend> findFriends(Long userId, Integer page, Integer pagesize) {
        //构建查询条件
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("created")))
                .limit(pagesize)
                .skip((page - 1) * pagesize);
        return mongoTemplate.find(query,Friend.class);
    }

    @Override
    public void deleteFriends(Long likeUserId, Long userId) {
        //删除第一条好友信息
        Query query1 = Query.query(Criteria.where("userId").is(userId).and("friendId").is(likeUserId));
        boolean aFlag = mongoTemplate.exists(query1, Friend.class);
        if (aFlag) {
            mongoTemplate.remove(query1, Friend.class);
        }
        //删除第二条好友信息
        Query query2 = Query.query(Criteria.where("userId").is(likeUserId).and("friendId").is(userId));
        boolean bFlag = mongoTemplate.exists(query2, Friend.class);
        if (bFlag) {
            mongoTemplate.remove(query2, Friend.class);
        }
    }
}
